<?php

namespace App\Admin\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Encore\Admin\Auth\Database\Administrator;
use App\crm_hetong;
use App\crm_hetongtype;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use App\Admin\Extensions\Tools\YuanGongGender;
use App\Admin\Extensions\Tools\PiliangGender;
use App\Admin\Extensions\Tools\FenPei;
class Crm_rukuController extends Controller
{
    use ModelForm;

    
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('合同入库管理');
            $content->description('列表');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('合同入库管理');
            $content->description('编辑');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('合同入库管理');
            $content->description('添加');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    // 合同表格
    protected function grid()
    {
        return Admin::grid(crm_hetong::class, function (Grid $grid) {
            $grid->model()->where('statue', 1);
            $grid->id('序号')->sortable();
            $grid->type('合同类型')->display(function ($name) {
                $list=crm_hetongtype::all()->pluck('title','id');
                return $list[$this->type];
            });
            $grid->hetong('合同号');
            $grid->statue('状态')->display(function ($name) {
                $list=['1'=>'入库','2'=>'领用','3'=>'核销'];
                return $list[$this->statue];
            });
            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                // 在这里添加字段过滤器
                $list=crm_hetongtype::all()->pluck('title','id');
                $filter->equal('type', '合同类型')->select($list);
                $filter->like('hetong', '合同号');
            });
            $grid->disableExport();//禁用导出按钮
            // $grid->disableRowSelector();//禁用行选择
            $grid->tools(function ($tools) {
                $tools->append(new PiliangGender());//调用批量添加按钮
                $tools->append(new YuanGongGender());//调用下单按钮
                $tools->batch(function ($batch) {
                    // $batch->disableDelete();//禁用批量删除
                    $batch->add('分配', new FenPei());
                });
            });
            $script_addones=<<<EOT
                $("#yuangong").css("display","none");
                $("#piliang").click(function(){
                    window.location.href="piliang"; 
                });

EOT;
                Admin::script($script_addones); 
        });
    }

    // 合同新增
    protected function form()
    {
        return Admin::form(crm_hetong::class, function (Form $form) {

            $form->display('id', '序号');
            $form->select('type','合同类型')->options(crm_hetongtype::all()->pluck('title','id'));
            $form->text('hetong','合同号');
            $form->hidden('statue','合同状态')->default(1);
        });
    }
    // 批量添加调用
    public function piliang()
    {
        return Admin::content(function (Content $content) {

            $content->header('合同入库管理');
            $content->description('添加');

            $content->body($this->tianjia());
        });
    }
    // 批量添加页面
    protected function tianjia()
    {
        return Admin::form(crm_hetong::class, function (Form $form) {

            $form->display('id', '序号');
            $form->select('type','合同类型')->options(crm_hetongtype::all()->pluck('title','id'));
            $form->text('kaishi','起始');
            $form->text('jieshu','结束');
            $form->hidden('statue','合同状态')->default(1);
            $form->setAction('pltianjia');
        });
    }
    // 批量添加执行
    public function pltianjia(Request $request)
    {
        $list=$request->except("_token","_previous_");
        $tianjia=$request->except("_token","_previous_","kaishi","jieshu");
        $qian=strstr($list['kaishi'],'-',true).'-';
        $kaishi=strstr($list['kaishi'],'-');
        $aa=ltrim(ltrim($kaishi,"-"),'0');
        $jieshu=strstr($list['jieshu'],'-');
        $bb=ltrim(ltrim($jieshu,"-"),'0');
        for ($x=$aa; $x<=$bb; $x++) {
            $res=$qian.str_pad($x,7,"0",STR_PAD_LEFT);
            $tianjia['hetong']=$res;
            crm_hetong::firstOrCreate($tianjia);
        } 
        $success = new MessageBag([
            'title'   => '添加成功',
        ]);
        return redirect(admin_url('crm_ruku'))->with(compact('success'));
    }
    // 调用分配页面
    public function fenpei(Request $request)
    {
        $list=$request->except("_token");
        $aa=\DB::table('admin_users')->where('username', 'like', '%'.$list['username'].'%')->get();
        if(!$aa->isEmpty()){
            return Admin::content(function (Content $content) use ($list) {
                $content->header(trans('admin::lang.administrator'));
                $content->description(trans('admin::lang.list'));
                $content->body($this->yuangong($list)->render());
            });
        }else{
            $error = new MessageBag([
                'title'   => '员工不存在，请重新分配！',
            ]);
            return back()->with(compact('error'));
        }
    }
    // 员工列表
    protected function yuangong($list)
    {
        return Administrator::grid(function (Grid $grid) use ($list) {
            $grid->model()->where('username', 'like', '%'.$list['username'].'%');
            $grid->id('序号')->sortable();
            $grid->username('员工姓名');
            // $grid->name(trans('admin::lang.name'));
            $grid->permissions('部门')->pluck('name')->label();
            $grid->roles(trans('admin::lang.roles'))->pluck('name')->label();
            $grid->rzdate('入职时间');
            $grid->created_at(trans('admin::lang.created_at'));
            $grid->updated_at(trans('admin::lang.updated_at'));
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if ($actions->getKey() == 1) {
                    $actions->disableDelete();
                }
            });
            $grid->disableFilter();//禁用查询过滤器
            $grid->disableCreation();//禁用导出按钮
            $grid->disableExport();//禁用导出按钮
            // 去掉操作按钮
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });
            $grid->actions(function ($actions) use ($list) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('<a href="fplingyong/'.$actions->getKey().'/'.$list['hetongid'].'" class="btn btn-sm btn-success" >分配</a>');
            });
            
        });
    }
    // 执行员工分配合同
    public function fplingyong($yuangongid,$hetongid)
    {
        $hetong = explode(',',$hetongid);
        foreach($hetong as $value)
        {
            $yuangong=\DB::table('admin_users')->where('id',$yuangongid)->pluck("username");
            $list=crm_hetong::find($value);
            $list->users_id=$yuangong[0];
            $list->statue=2;
            $list->save();
        }
        $success = new MessageBag([
            'title'   => '分配成功',
        ]);
        return redirect(admin_url('crm_ruku'))->with(compact('success'));
    }
}
